import { RawMessage, Player, world } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";

/**
 * A reading, use `SimpleReadng` to create a reading in game.
 * @since 0.3.1
 */
export class Reading {
  /**
   * Id of the reading.
   */
  id: string;
  /**
   * Title of the reading.
   */
  title: string | RawMessage;
  /**
   * Body of the reading.
   */
  body: string | RawMessage;
  constructor(
    id: string,
    title: string | RawMessage,
    body: string | RawMessage,
  ) {
    this.id = id;
    this.title = title;
    this.body = body;
  }
}

/**
 * Create a simple reading in game.
 * @since 0.3.1
 * @example createASimpleReading.ts
 *  ```ts
 * const EXAMPLE_READING = new SimpleReading("test:example_reading","示例阅读物", "示例内容");
 * ```
 */
export class SimpleReading extends Reading {
  /**
   * If true, the reading will not display when player use the item.
   */
  isChapter: boolean;
  /**
   * Display the reading to a player.
   */
  display(player: Player): void {
    const FORM = new ActionFormData()
      .title(this.title)
      .body(this.body)
      .button({ translate: "gui.ok" });
    FORM.show(player);
  }
  constructor(
    id: string,
    title: string | RawMessage,
    body: string | RawMessage,
    isChapter = false,
  ) {
    super(id, title, body);
    this.isChapter = isChapter;
    if (isChapter === false) {
      world.afterEvents.itemUse.subscribe((event) => {
        if (event.itemStack.typeId === id) {
          this.display(event.source);
        }
      });
    }
  }
}

/**
 * Create a reading with chapters.
 * @since 0.4.0
 */
export class ChapterReading extends Reading {
  /**
   * Chapters of the reading.
   */
  chapters: SimpleReading[];
  /**
   * Display the reading to a player.
   */
  display(player: Player): void {
    const FORM = new ActionFormData().title(this.title).body(this.body);
    this.chapters.forEach((chapter) => {
      FORM.button(chapter.title);
    });
    FORM.show(player).then((response) => {
      if (response.canceled || response.selection === undefined) {
        return;
      }
      const chapter: SimpleReading = this.chapters[response.selection];
      chapter.display(player);
    });
  }
  constructor(
    id: string,
    title: string | RawMessage,
    body: string | RawMessage,
    chapters: SimpleReading[],
  ) {
    super(id, title, body);
    this.chapters = chapters;
    world.afterEvents.itemUse.subscribe((event) => {
      if (event.itemStack.typeId === this.id) {
        this.display(event.source);
      }
    });
  }
}
